package com.j180;

import com.j180.config.SpringConfig;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * Hello world! 
 *
 */
public class App{
    public static void main( String[] args ){
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8081);
        Connector connector = tomcat.getConnector();
        Context context = tomcat.addContext("pet", null);

        //注册dispatcherServlet
        DispatcherServlet dispatcherServlet = new DispatcherServlet();
        AnnotationConfigWebApplicationContext cxt = new AnnotationConfigWebApplicationContext();
        //读取spring的核心配置文件
        cxt.register(SpringConfig.class);
        //设置全局对象
        cxt.setServletContext(context.getServletContext());
        dispatcherServlet.setApplicationContext(cxt);
        Wrapper servlet= tomcat.addServlet(context, "dispatcherServlet", dispatcherServlet);
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");

        FilterDef encodingFilter = new FilterDef();//Filter定义
        encodingFilter.setFilterName("encodingFilter");
        encodingFilter.setFilterClass(CharacterEncodingFilter.class.getName());
        encodingFilter.addInitParameter("encoding", "utf-8");
        context.addFilterDef(encodingFilter);
        FilterMap filterMap = new FilterMap();//Filter路径映射
        filterMap.setFilterName("encodingFilter");
        filterMap.addURLPattern("/*");
        context.addFilterMap(filterMap);

        //支持restful
        FilterDef hiddenMethod = new FilterDef();//Filter定义
        hiddenMethod.setFilterName("hiddenMethod");
        hiddenMethod.setFilterClass(HiddenHttpMethodFilter.class.getName());
        context.addFilterDef(hiddenMethod);
        FilterMap filterMap2 = new FilterMap();//Filter路径映射
        filterMap2.setFilterName("hiddenMethod");
        filterMap2.addURLPattern("/*");
        context.addFilterMap(filterMap2);

        try {
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }
}
